<?php
declare (strict_types = 1);
namespace app\admin\controller;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\View;

class UserMail extends Backend
{
    public function initialize() {
        parent::initialize();
        $this->_mod  = new \app\admin\model\UserMail();
    }

    public function _before_index(){
        $where = array();
        $keyword =  request()->param('keyword');
        if($keyword) $where[]=array('title','like','%'.$keyword.'%');
        View::assign('search', array(
            'keyword'=>$keyword,
        ));
        $this->_list($this->_mod, $where, 'id', 'desc');
    }



    public function add() {
        if(request()->isPost()) {
            $data = request()->post();
            //用户
            $to_name = $data['to_name'];
            //发送者
            // $from_user = session('admin');
            //$from_name = $from_user['username'];
            //接收者
            $to_user = array(array('id' => '0'));
            if ($to_name) {
                //指定用户
                $to_name = explode(',', $to_name);
    //                var_dump($to_name);exit;
                //$to_name = array('0'=>'feefasf','1'=>'111111');
                $where[] = ['username', 'in', $to_name];
                $to_user = Db::name('user')->field('id,username')->where($where)->select()->toArray();
            }

            //内容
            //自定义
            $info = $data['info'];
            $title = $data['title'];

            if (!$info) return fail(0, '消息不能为空');
            if (!$title) return fail(0, '标题不能为空');
            //逐条发送
            foreach ($to_user as $val) {
                $data_arr = [
                    'fromid' => 0,
                    'toid' => (int)$val['id'],
                    'info' => $info,
                    'title' => $title,
                    'is_sys' => '1',
                    'create_time' => time()
                ];
                $this->_mod->create($data_arr)->getData('id');
            }
            return success(1,'操作成功','');
        }else{
            if(request()->isAjax()){
                $data=[1,'',view('edit')];
                return json($data);
            }else{
                return view('edit');
            }
        }
    }


}


